package com.itheima.reggie.common;

import com.itheima.reggie.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.FileNotFoundException;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        String exMessage = ex.getMessage();
        log.error(exMessage);
        if(exMessage.contains("Duplicate entry")){
            String[] s = exMessage.split(" ");
            String message = s[2]+"已存在!";
            return R.error(message);
        }
        return R.error("未知错误！");
    }

    @ExceptionHandler(CustomException.class)
    public R<String> customExceptionHandler(CustomException ex){
        log.error(ex.getMessage());
        return R.error(ex.getMessage());
    }

    @ExceptionHandler(FileNotFoundException.class)
    public R<String> fileNotFoundException(FileNotFoundException ex){
        return R.error(ex.getMessage());
    }


}
